package com.gzhryc.net_marketing.cloud.account.services;

import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.Conditions;
import com.gzhryc.jdbc.MultiDBTools;
import com.gzhryc.net_marketing.cloud.MarketConstants;
import com.gzhryc.net_marketing.cloud.account.dao.CloudPayAccountOperateRecordDao;
import com.gzhryc.net_marketing.cloud.account.dao.db.CloudPayAccountOperateRecord;
import com.gzhryc.net_marketing.cloud.account.services.dto.CloudPayAccountOperateRecordSearch;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class CloudPayAccountOperateRecordService {

    static Logger log = Logger.getLogger(CloudPayAccountOperateRecordService.class);

    public static CloudPayAccountOperateRecordService self() {
        return MultiDBTools.getService(MarketConstants.JDBC_KEY,CloudPayAccountOperateRecordService.class, true);
    }

    CloudPayAccountOperateRecordDao dao;

    public CloudPayAccountOperateRecordService(String jdbcKey) {
        this.dao = new CloudPayAccountOperateRecordDao(jdbcKey);
    }

    public List<CloudPayAccountOperateRecord> findBySearch(CloudPayAccountOperateRecordSearch search, Integer pageNo, Integer pageLimit){
        Conditions conditions = dao.buildConditions(search);
        conditions.desc("createDate");
        try {
            return dao.findByCondition(conditions,pageNo,pageLimit);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public Long countBySearch(CloudPayAccountOperateRecordSearch search){
        Conditions conditions = dao.buildConditions(search);
        try {
            return dao.count(conditions);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return 0L;
    }

    public boolean add(CloudPayAccountOperateRecord operateRecord) throws LogicException {
        operateRecord.setCreateDate(new Date());
        try {
            return dao.insert(operateRecord) > 0;
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return false;
    }

    public boolean deleteByAccountId(Long accountId){
        if(accountId != null){
            Conditions conditions = new Conditions(CloudPayAccountOperateRecord.class);
            conditions.and().is("accountId",accountId);

            try {
                return dao.deleteByCondition(conditions) >= 0;
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return false;
    }
}
